<template>
  <div style="width: 100%">
    <el-dialog
      v-model="innerVisible"
      width="500"
      title="流程返退"
      append-to-body
    >
      <el-form ref="flowFormRef" v-model="backForm" :rules="rules">
        <el-form-item label="返退流程">
          <el-select v-model="backForm.backFlowState">
            <el-option label="请选择" :value="0" />
            <el-option label="到单录入" :value="-1" />
            <el-option label="确认收款" :value="-2" />
            <el-option label="业务提单" :value="-3" />
            <el-option label="内勤审核/分单" :value="-4" />
          </el-select>
        </el-form-item>
        <el-form-item label="返退原因">
          <el-input
            v-model="backForm.ReturnReason"
            placeholder="请输入返退原因"
          />
        </el-form-item>
        <div style="margin-top: 10px; display: flex; justify-content: end">
          <el-button type="primary" @click="handleBackContract">
            确认返退
          </el-button>
        </div>
      </el-form>
    </el-dialog>
    <div style="height: 100px; padding-top: 20px">
      <div style="width: 80%; float: left">
        <el-steps align-center :active="currFlow" finish-status="success">
          <!-- <el-step title="商机跟进" /> -->
          <el-step title="签约" />
          <el-step title="到单录入" />
          <el-step title="确认收款" />
          <el-step title="业务提单" />
          <el-step title="审核/分单1" />
          <el-step title="复核/分单2" />
          <el-step v-if="currFlow > 9" title="服务中" />
        </el-steps>
      </div>
      <div style="width: 20%; float: left">
        <el-button
          v-if="finishBtnName"
          :type="finishBtnColor"
          @click="finishContract"
        >
          {{ finishBtnName }}
        </el-button>
        <el-button
          v-if="pageflow > 2 && currFlow > 1 && currFlow < 7 && pageflow !== 4"
          type="info"
          @click="handleBackDialog"
        >
          流程返退
        </el-button>
      </div>
    </div>
    <el-alert
      v-if="
        CurrOrderFlow.OrderFlowState < 0 &&
        Math.abs(CurrOrderFlow.OrderFlowState) == currFlow
      "
      :title="
        CurrOrderFlow.FlowStaffName +
        CurrOrderFlow.addTime +
        CurrOrderFlow.OrderFlowName +
        '，原因：' +
        CurrOrderFlow.ReturnReason
      "
      type="error"
      closable
      close-text="处理错误后即可关闭提示 ×"
      @close="hello"
    />
  </div>
</template>

<script>
  import { saveOrderFlow } from '@/api/businessOrder'

  export default defineComponent({
    name: 'OrderFlow',
    props: {
      pageflow: {
        type: Number,
        default: 0,
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        BusinessClass: {},
        CustomerInfo: {},
        CurrOrderFlow: {},
        flowFormRef: null,
        backForm: { backFlowState: 0 },
        OrderFlowRef: null,
        OrderInfo: {},
        infoMsg: true,
        Licenses: {},
        ProductList: [],
        PaymentList: [],
        InvoicingList: [],
        WorkTasks: [],
        chageOrderFlow: {
          OrderID: 0,
          OrderFlowState: 0,
        },
        currFlow: 0,
        finishBtnName: '',
        finishBtnColor: 'danger',
        innerVisible: false,
        rules: {},
      })
      const showOrder = (
        BusinessClass,
        info,
        ProductList,
        PaymentList,
        InvoicingList,
        WorkTasks,
        OrderFlow,
        Licenses,
        CustomerInfo
      ) => {
        state.BusinessClass = BusinessClass
        state.CurrOrderFlow = Object.assign({}, OrderFlow)
        state.OrderInfo = Object.assign({}, info)
        state.ProductList = ProductList
        state.PaymentList = PaymentList
        state.CustomerInfo = CustomerInfo
        state.InvoicingList = InvoicingList
        state.WorkTasks = WorkTasks
        state.Licenses = Licenses
        state.currFlow = Math.abs(info.OrderFlowState)

        if (props.pageflow == 2) {
          if (state.currFlow == 1) {
            state.finishBtnName = '完成到单录入'
            state.finishBtnColor = 'danger'
          } else if (state.currFlow == 2) {
            state.finishBtnName = '已完成到单录入'
            state.finishBtnColor = 'info'
          } else {
            state.finishBtnName = ''
          }
        }
        if (props.pageflow == 3) {
          if (state.currFlow == 2) {
            state.finishBtnName = '完成确认收款'
            state.finishBtnColor = 'danger'
          } else if (state.currFlow == 3) {
            state.finishBtnName = '已完成确认收款'
            state.finishBtnColor = 'info'
          } else {
            state.finishBtnName = ''
          }
        }
        if (props.pageflow == 4) {
          if (state.currFlow == 3) {
            state.finishBtnName = '完成提单'
            state.finishBtnColor = 'danger'
          } else if (state.currFlow == 4) {
            state.finishBtnName = '已完成提单'
            state.finishBtnColor = 'info'
          } else {
            state.finishBtnName = ''
          }
        }
        if (props.pageflow == 5) {
          if (state.currFlow == 4) {
            if (state.BusinessClass.BusinessClassID == 8) {
              state.finishBtnName = '完成审核不分单'
              state.finishBtnColor = 'danger'
            } else {
              state.finishBtnName = '完成审核/分单'
              state.finishBtnColor = 'danger'
            }
          } else if (state.currFlow == 5) {
            if (state.BusinessClass.BusinessClassID == 8) {
              state.finishBtnName = '已完成审核'
              state.finishBtnColor = 'info'
            } else {
              state.finishBtnName = '已完成审核/分单'
              state.finishBtnColor = 'info'
            }
          }
        }
        if (props.pageflow == 6) {
          if (state.currFlow == 5) {
            state.finishBtnName = '完成运营分单'
            state.finishBtnColor = 'danger'
          } else if (state.currFlow == 6) {
            state.finishBtnName = '已完成运营分单'
            state.finishBtnColor = 'info'
          } else {
            state.finishBtnName = ''
          }
        }
        if (state.currFlow > 7) {
          state.finishBtnName = '已进入服务环节'
          state.finishBtnColor = 'success'
        }
      }

      const finishContract = async () => {
        console.log('state.OrderInfo', state.OrderInfo)

        if (state.BusinessClass.isContract) {
          if (state.BusinessClass.isSubmitOrder) {
            if (
              props.pageflow == 4 &&
              JSON.parse(state.OrderInfo.OrderAttachFile).length === 0
            ) {
              $baseMessage(
                '您还没有上传合同附件！',
                'warning',
                'vab-hey-message-warning'
              )
              return false
            }
          } else {
            if (JSON.parse(state.OrderInfo.OrderAttachFile).length === 0) {
              $baseMessage(
                '您还没有上传合同附件！',
                'warning',
                'vab-hey-message-warning'
              )
              return false
            }
          }
        }

        if (
          state.OrderInfo.InputState == 0 ||
          !state.OrderInfo.OrderCode ||
          !state.OrderInfo.SignOrderDate
        ) {
          $baseMessage(
            '您还没有录入合同信息，请务必录入合同信息，并保存合同信息',
            'warning',
            'vab-hey-message-warning'
          )
          return false
        }

        let ProductcTotalMoney = 0

        if (state.ProductList.length == 0) {
          $baseMessage(
            '您还没有录入业务产品，请务必录入所签约业务产品',
            'warning',
            'vab-hey-message-warning'
          )
          return false
        } else {
          state.ProductList.forEach((item) => {
            ProductcTotalMoney += item.ProductMoney
          })
        }

        if (
          state.ProductList.length !== 0 &&
          ProductcTotalMoney != 0 &&
          state.OrderInfo.OrderFenqi == 0
        ) {
          if (
            state.PaymentList.length == 0 &&
            state.BusinessClass.isPayment === 1
          ) {
            $baseMessage(
              '您还没有录入收款',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }

          // if (
          //   state.InvoicingList.length == 0 &&
          //   state.BusinessClass.isVoicing === 1
          // ) {
          //   $baseMessage(
          //     '您还没有录入开票',
          //     'warning',
          //     'vab-hey-message-warning'
          //   )
          //   return false
          // }

          // 合同收款总额不能超过总合同额+备付金
          let isPaymentMoney = 0
          for (let index = 0; index < state.PaymentList.length; index++) {
            isPaymentMoney += Number(state.PaymentList[index].PaymentMoney)
          }
          const isOrderTotalMoney =
            Number(state.OrderInfo.OrderTotalMoney) +
            Number(state.OrderInfo.ReserveMoney)

          console.log(isPaymentMoney, isOrderTotalMoney, '什么！！！！！！')

          if (isOrderTotalMoney < isPaymentMoney) {
            $baseMessage(
              '合同收款总额不能超过总合同额+备付金',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }
        }

        if (props.pageflow == 5) {
          if (
            state.WorkTasks.length == 0 &&
            state.BusinessClass.BusinessClassID != 8
          ) {
            $baseMessage(
              '您并没有进行任何分单或任务分派，请进行分单或任务分派！',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }
        }

        if (props.pageflow === 2) {
          if (state.BusinessClass.BusinessClassID === 3) {
            // 上传合同
            if (state.OrderInfo.isOrderAttach === 0) {
              $baseMessage(
                '您还没有上传合同附件，请务必扫描或拍照上传',
                'warning',
                'vab-hey-message-warning'
              )
              return false
            }
          }
        }

        if (props.pageflow === 4 && state.BusinessClass.isSubmitOrder === 1) {
          // 业务联系人
          console.log(state.CustomerInfo, '客户信息')
          if (
            !state.CustomerInfo.Address ||
            !state.CustomerInfo.Telphone ||
            !state.CustomerInfo.LegalPerson ||
            !state.CustomerInfo.LegalMobile ||
            !state.CustomerInfo.BusinessPerson ||
            !state.CustomerInfo.BusinessPersonMobile ||
            !state.CustomerInfo.SalesProducts ||
            !state.CustomerInfo.SalesArea ||
            !state.CustomerInfo.CustomerGroup ||
            !state.CustomerInfo.City ||
            !state.CustomerInfo.Industry ||
            !state.CustomerInfo.CustomerAllName
          ) {
            state.infoMsg = true
          } else {
            state.infoMsg = false
          }
          if (state.infoMsg) {
            $baseMessage(
              '您还没有补全客户信息，请务填写',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }
          // 执照
          if (state.Licenses.LicensePhoto.length === 0) {
            $baseMessage(
              '您还没有上传执照，请务必扫描或拍照上传',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }
          // 上传合同
          if (state.OrderInfo.isOrderAttach === 0) {
            $baseMessage(
              '您还没有上传合同附件，请务必扫描或拍照上传',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }
          // 绑定店铺
          if (!limit()) {
            $baseMessage(
              '您还没有绑定店铺，请点击补充详情绑定',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }
        }

        if (props.pageflow == 3) {
          // 检测收款条目，是否已全部进行了确认收款；

          let checkPayok = 0

          state.PaymentList.forEach((item) => {
            if (item.PaymentState === 1) {
              checkPayok++
            }
          })
          console.log(checkPayok, '检测收款条目，是否已全部进行了确认收款；')
          if (checkPayok !== state.PaymentList.length) {
            $baseMessage(
              '您还有没有确认的收款，请先完成所有收款确认',
              'warning',
              'vab-hey-message-warning'
            )
            return false
          }
          // 如没有全部进行收款，则提示不可进行“完成确认收款”
        }

        state.chageOrderFlow = {
          OrderID: state.OrderInfo.OrderID,
          OrderFlowState: props.pageflow,
        }
        const { msg } = await saveOrderFlow(state.chageOrderFlow)
        $baseMessage(msg, 'success', 'vab-hey-message-success')
        emit('fetch-data')
      }

      const handleBackDialog = () => {
        state.innerVisible = true
      }

      const handleBackContract = async () => {
        if (state.backForm.backFlowState == 0) {
          $baseMessage('请选择回退流程', 'warning', 'vab-hey-message-warning')
          return false
        } else {
          if (!state.backForm.ReturnReason) {
            $baseMessage('请输入返退原因', 'warning', 'vab-hey-message-warning')
          } else {
            console.log(props.pageflow, props.pageflow)
            state.OrderInfo.ReturnReason = state.backForm.ReturnReason
            state.OrderInfo.OrderFlowState = state.backForm.backFlowState
            state.OrderInfo.OrderState = Math.abs(state.backForm.backFlowState)
            const { msg } = await saveOrderFlow(state.OrderInfo)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            state.innerVisible = false
          }
        }
      }
      const limit = () => {
        console.log(
          state.ProductList,
          ' state.ProductList state.ProductList state.ProductList'
        )

        for (let index = 0; index < state.ProductList.length; index++) {
          if (state.ProductList[index].BindStoreID === 0) {
            console.log(state.ProductList[index].BindStoreID, '123')
            return false
          }
        }
        return true
      }

      return {
        ...toRefs(state),
        limit,
        showOrder,
        finishContract,
        handleBackDialog,
        handleBackContract,
      }
    },
  })
</script>
